package com.jcl.core.web.utils;

import org.owasp.esapi.ESAPI;
import org.owasp.esapi.codecs.MySQLCodec;
import org.owasp.validator.html.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @ClassName XssUtils

 * @Author yyliu
 * @Date 2018/9/19 15:27
 * @Version 1.0
 **/
public class XssUtils {

    private static final Logger logger = LoggerFactory.getLogger(XssUtils.class);

    private static Policy policy = null;
    private static AntiSamy antiSamy = null;

    static {

        String path = XssUtils.class.getClassLoader().getResource("esapi/antisamy-anythinggoes.xml").getFile();
        if (path.startsWith("file")) {
            path = path.substring(6);
        }
        try {
            policy = Policy.getInstance(path);

            if (null != policy) {
                antiSamy = new AntiSamy(policy);
            }
        } catch (PolicyException e) {
            logger.error("policy init fail !!!");
            logger.error(e.getMessage(), e);
        }

    }

    public static String xssClean(String content) {

        if (null == antiSamy) {
            antiSamy = new AntiSamy(policy);
        }
        try {
            CleanResults results = antiSamy.scan(content);
            return results.getCleanHTML();
        } catch (ScanException e) {
            e.printStackTrace();
        } catch (PolicyException e) {
            e.printStackTrace();
        }
        return content;
    }

    public static String sqlClean(String content) {
        MySQLCodec codec = new MySQLCodec(MySQLCodec.Mode.STANDARD);
        String result = ESAPI.encoder().encodeForSQL(codec, content);
        return result;
    }

    public static void main(String[] args) {
        String text = "select * from a  <a href=\"http://www.baidu.com/a\" onclick=\"alert(1);\">sss</a><script>alert(0);</script>sss";
        System.out.println(xssClean(text));
        System.out.println(sqlClean(text));


    }
}
